package com.dk.shiro;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class ShiroController {
//shiro是基于过滤器,开启shiro的过滤器
    //最核心的类
    @Bean
    public ShiroFilterFactoryBean ShiroBean(@Autowired DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean sfb = new ShiroFilterFactoryBean();
        //设置过滤器链
        Map<String,String> map = new HashMap<>();
              map.put("/user/getInfo","anon");
              map.put("/user/deleteLogin","logout");
              map.put("/menu/toztr","perms[menu_toShow]");
              map.put("/TP/toShow","perms[TP_toShow]");
              map.put("/role/toShow","perms[role_toShow]");
              map.put("null","perms[nullsss]");
              map.put("/car/toShow","perms[car_toShow]");
              map.put("/role/toAdd","perms[role_toAdd]");
              map.put("/car/toAdd","perms[car_toAdd]");
              map.put("/car/deleteAll","perms[car_deleteAll]");
              map.put("/role/addInfo","perms[role_addInfo]");
              map.put("/**","authc");
              sfb.setLoginUrl("/user/toShow");
              sfb.setUnauthorizedUrl("/user/unauthor");
              sfb.setFilterChainDefinitionMap(map);
        //设置安全管理器
        sfb.setSecurityManager(defaultWebSecurityManager);
        return sfb;
    }
//创建自己的remdl
    @Bean
    public LoginController loginController(@Autowired HashedCredentialsMatcher hashedCredentialsMatcher){
        LoginController loginController = new LoginController();
        loginController.setCredentialsMatcher(hashedCredentialsMatcher);
        return loginController;

    }
//创建安全管理器的对象

    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(@Autowired LoginController loginController){
        DefaultWebSecurityManager dwsm = new DefaultWebSecurityManager();
        //安全管理器 关联登录授权的功能
        dwsm.setRealm(loginController);
        return dwsm;
    }

    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher (){
        HashedCredentialsMatcher hcm = new HashedCredentialsMatcher();
        hcm.setHashAlgorithmName("MD5");
        //撒盐次数
        hcm.setHashIterations(10);
        //设置编码
        hcm.setStoredCredentialsHexEncoded(true);
        return hcm;
    }
    @Bean
    public ShiroDialect shiroDialect (){
        return new ShiroDialect();
    }
}
